// pages/oerderDetail.js
// 获取应用实例
const app = getApp()
const $req = require('../../utils/req.js') //接口封装文件
//地图
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    firstEnter:false,
    dateMask:true,
    scheduleLegend: [{
      name: '可预订',
      color: '#D1D1D1',
    }, {
      name: '不可预订',
      color: '#777575'
    }, {
      name: '已预订',
      color: '#EA5826',
    }, {
      name: '已选中',
      color: '#FDB644',
    }],
    roomInfo: {},
    roomTimes: [],
    selectTimes: [],
    goodsList: [],
    Descr:null,
    totalPrice: '0.00',
    dis: 0,
    disAmount: '0.00',
    goodsListTotalPrice: '0.00',
    finsTotalprice: '0.00',
    timeInterval: [0, 0],
    isIphoneX: app.globalData.systemInfo.screenHeight >= 812 ? true : false,
    bannerList: [
      '../../public/cache/banner.png',
      '../../public/cache/roomImg.png'
  ], 
  //轮播图
    date:new Date().toISOString().substring(0, 10),
    openstid:null,
    starttime:null,
    endtime:null,
    adddays:0,
    deldays:0,
    userInfo:null,//用户缓存
    RoomID:null,//会议室ID
    myval:null,
    onifrules:false,
    onword:'',
    oktime:0,
  },
  //实时textarea
  inputstextarea(e){
    let _this = this
    console.log(e)
    _this.setData({
      Descr:e.detail.value
    })
  },
  //打开时间选择器
  openDateMask(e){
    let _this = this
    _this.setData({
      dateMask:false
    })
  },
  //时间选择器选中时间改变时间列表
  getdate(e){
    let that = this;
    console.log(e.detail)
    console.log(that.data.openstid)
    that.setData({
      date:e.detail.datestr
    })
    that.getRoomTimesInfo(that.data.openstid, e.detail.datestr)
  },
  //上一日
  onDateMaskdel(e){
    let that = this;
    let a = this.data.date.replace(/-/g, '/')
    let time = Date.parse(a);
    var adddays =  that.getActiveDate(time,1,false)
    that.setData({
      adddays:adddays
    })
    that.setData({
      date:adddays,
    })
    that.getRoomTimesInfo(that.data.openstid, adddays)
  },
  //下一日
  onDateMaskadd(e){
    let that = this;
    let a = this.data.date.replace(/-/g, '/')
    let time = Date.parse(a);
    var deldays = that.getActiveDate(time)
    that.setData({
      deldays:deldays,
    })
    that.setData({
      date:deldays,
    })
     that.getRoomTimesInfo(that.data.openstid, deldays)
  },

  getActiveDate:function(time, day=1, direction=true){
    let that=this
   let date = null;
   if(direction){
        date = new Date(time + 24*day*60*60*1000);
    }else{
       date = new Date(time - 24*day*60*60*1000);
    } 
     return that.time(date)
},
time(data) {
  let that=this
  let tomorrow = new Date(data);
  let year = tomorrow.getFullYear(); //获取年
  let month = tomorrow.getMonth() + 1; //获取月
  let date = tomorrow.getDate(); //获取日
  let tomorrowSS = year + '-' + month + "-" + date       
   return  tomorrowSS
}
,
  onDateMaskdaylist(e){
      let _this = this
      // let id =e.currentTarget.dataset.id
      let openstid = _this.data.openstid
      let url = "../manydays/manydays?id="+openstid
      wx.navigateTo({url: url})
  },
  onSearchInputEvent(e){
    let that = this;
    let value = e.detail.dateMask;
    console.log(value);
      that.setData({
        dateMask:value
      })
     
  },
  onSearchEvent(e){
    let that = this;
    let select = e.detail.selectDays;
    let value = e.detail.clreashuju.dateMask; 
    that.setData({
      selectTimes:select,
      dateMask:value
    })
  },

  getRoomInfo(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID
    }
    $req.getRoomInfo(data).then(res => {
      _this.setData({
        roomInfo: res.DATA,
      
      })
      if(res.DATA.ImgList!=null){
        _this.setData({
          bannerList: res.DATA.ImgList
        }) 
      }
    })
  },

  // 获取会议室可用时间段  传参数 会议室id和时间
  getRoomTimesInfo(RoomID, Mdate) {
    let _this = this
    let data = {
      RoomID: RoomID,
      Mdate: Mdate,
    }
    $req.getRoomTimesInfo(data).then(res => {
      let result = res.DATA
      result.forEach((item, index) => {
        item.timePoint = item.FromTo.split("-")[0]
          if(item.IsOrder){
                    item.CanOrder= true
                  }
        item.checkFlag=false
      });
      _this.setData({
        roomTimes: result,
      })
    })
  },

  getGoodsList(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID,
    }
    $req.getGoodsList(data).then(res => {
      let result = res.DATA
      result.forEach((item, index) => {
        item.num = 0
        item.Price = item.Price.toFixed(2)
        item.totalPrice = (item.Price * item.num).toFixed(2)
      })
      _this.setData({
        goodsList: res.DATA
      })
    })
  },

  // 点击时间表格
  touchTimesTable(e) {
    let _this = this
    let checkTimeIndex = e.currentTarget.dataset.index //用户点击的时间索引
    let typeValue = _this.data.roomInfo.SortNm == "大型会议室" ? 7 : 3 //不算首位
    // let roomTiemsCopy = Object.create(_this.data.roomTimes) //拷贝数据
    let roomTiemsCopy = [..._this.data.roomTimes] //拷贝数据
    let timeInterval = _this.data.timeInterval
    if (roomTiemsCopy[checkTimeIndex].checkFlag) {
      // 点击项为选中的
      if ((checkTimeIndex - timeInterval[0]) > typeValue) {
        roomTiemsCopy.forEach((item, index) => {
          item.checkFlag = false
          if (timeInterval[0] <= index && index < checkTimeIndex) {
            timeInterval[0] = timeInterval[0]
            timeInterval[1] = checkTimeIndex
            item.checkFlag = true
          }
        })
      } else {
        // 剩余区间不足最小范围
        roomTiemsCopy.forEach((item, index) => {
          timeInterval[0] = 0
          timeInterval[1] = 0
          item.checkFlag = false
        })
      }
    } else {
      console.log(roomTiemsCopy);
      // 点击项为未选择的
      if (timeInterval[0] == 0 && timeInterval[1] == 0) {
        // 初始状态
        if ((checkTimeIndex + typeValue) > roomTiemsCopy.length - 1) {
          // 判断点击点位是否超过可选
          return
        }
        let canCheck = false
        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= (checkTimeIndex + typeValue)) {
            if (!item.CanOrder || item.IsOrder) {
              canCheck = true
            }
          }
        })
        if (canCheck) {
          return
        }
        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= (checkTimeIndex + typeValue)) {
            timeInterval[0] = checkTimeIndex
            timeInterval[1] = (checkTimeIndex + typeValue)
            item.checkFlag = true
          }
        })
      } else {
        let canCheck = false
        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= timeInterval[1]) {
            if (!item.CanOrder || item.IsOrder) {
              canCheck = true
            }
          }
        })

        if (canCheck) {
          return
        }

        // 二次点击
        if (checkTimeIndex < timeInterval[0]) {
          roomTiemsCopy.forEach((item, index) => {
            if (checkTimeIndex <= index && index <= timeInterval[1]) {
              timeInterval[0] = checkTimeIndex
              timeInterval[1] = timeInterval[1]
              item.checkFlag = true
            }
          })
        } else if (checkTimeIndex > timeInterval[1]) {
          roomTiemsCopy.forEach((item, index) => {
            if (timeInterval[0] <= index && index <= checkTimeIndex) {
              timeInterval[0] = timeInterval[0]
              timeInterval[1] = checkTimeIndex
              item.checkFlag = true
            }
          })
        }
      }
    }
    let oktime = (timeInterval[1]-timeInterval[0]+1)/2>1?(timeInterval[1]-timeInterval[0]+1)/2:0
    _this.setData({
      oktime:oktime,
      roomTimes: roomTiemsCopy,
      timeInr: timeInterval
    })
    _this.totalPrice()
    _this.finsTotalprice()
  },

  // 计算总金额
  totalPrice() {
    let _this = this
    let roomTiemsCopy = Object.create(_this.data.roomTimes)
    let totalPrice = 0
    let oktime = _this.data.oktime
    let Price = 0
    roomTiemsCopy.forEach((item, index) => {
      if (item.checkFlag) {
         Price = item.Price
        totalPrice += item.Price
      }
    })
      //超过8小时按照减一小时计算
      if(oktime>8){
        totalPrice = totalPrice*1-Price*2
        if(totalPrice<Price*2*8){
          totalPrice = Price*2*8
        }
      }
      let disAmount =   (totalPrice*_this.data.dis).toFixed(2)*1
      _this.setData({
        totalPrice: (totalPrice).toFixed(2),
        disAmount: disAmount,
      })
  },
  changeGoodsNum(e) {
    let _this = this
    let data = e.currentTarget.dataset
    let goodsList = _this.data.goodsList
    let goods = goodsList[data.index]
    switch (data.type) {
      case "+":
        goods.num += 1
        break
      case "-":
        goods.num -= 1
        break
    }
    if (goods.num < 0) {
      goods.num = 0
    }
    goods.totalPrice = (goods.num * goods.Price).toFixed(2)
    _this.goodsListTotalPrice()
    _this.finsTotalprice()
    _this.setData({
      goodsList: goodsList,
    })
    console.log(goodsList)
  },

  finsTotalprice() {
    let _this = this
    _this.setData({
      finsTotalprice: (parseFloat(_this.data.disAmount) + parseFloat(_this.data.goodsListTotalPrice)).toFixed(2),
    })
  },

  goodsListTotalPrice() {
    let _this = this
    let goodsListTotalPrice = 0
    let goodsList = _this.data.goodsList
    goodsList.forEach((item, index) => {
      goodsListTotalPrice += parseFloat(item.totalPrice)
    })
    _this.setData({
      goodsListTotalPrice: goodsListTotalPrice.toFixed(2)
    })
  },
  saveOrder(e) {
    let _this = this
    let token = wx.getStorageSync("token")?wx.getStorageSync("token"):''
    let RoomID = _this.data.roomInfo.RoomID?_this.data.roomInfo.RoomID:''
    let Mdate =  _this.data.date?_this.data.date:''
    let MdateTo =  _this.data.date?_this.data.date:''
    let Descr = _this.data.Descr ? _this.data.Descr  : ''
    let roomTimes = _this.data.roomTimes
    let Details = []
    let goodsList= _this.data.goodsList?_this.data.goodsList:[]
    let Goods = []
    //时间改变格式
    var TimesID = []
    var Mdates = []
    let myval = _this.data.myval
    if(myval==null){
      wx.showToast({
        title: '请阅读预订须知',
        icon: 'error',
        duration: 2000
      })
    }else{
      roomTimes.forEach((item, index) => {
        if (item.checkFlag) {
          TimesID+= item.TimesID+','
          Mdates = item.Mdate
        }
      })
  
      if(TimesID.length==0){
        wx.showToast({
          title: '请选择时间预定',
          icon: 'error',
          duration: 2000
        })
      }else{
        Details.push({
          Mdate: Mdates,
          TimesID: TimesID,
        });
     
     
      //商品改变格式
      var Nums = []
      goodsList.forEach((item, index) => {
        if(item.num!=0){
          Goods.push({
            GoodsID: item.GoodsID,
            Nums: item.num
          })
        }
      })
      let data = {
        Token: wx.getStorageSync("token") ? wx.getStorageSync("token") : '',
        OrderNo: '', //	string	订单编号(新订单为空)
        RoomID: RoomID,
        Mdate: Mdate, //date	会议室预订日期(开始日期）
        MdateTo: MdateTo, //	date	会议室预订日期(结束日期）
        Descr: Descr, //	string	订单备注
        Details: Details, //	Json	列表
        Goods: Goods, // Goods 商品
      }
      var jsonObj = JSON.stringify(data);
      wx.request({
        url: 'https://www.yulonging.com/dwweb/wxapi.ashx?cmd=saveorder',
        data: jsonObj,
        method: "post",
        success(res) {
            if(res.data.STATUS=='Success'){
            wx.navigateTo({
              url: '/pages/orderInfo/orderinfodetail?OrderNo='+res.data.DATA.OrderNo+'&TotalFee='+res.data.DATA.TotalFee,
            })
            }else{

              //刷新时间选择列表
              _this.getGoodsList(RoomID)
              _this.setData({
                Details:[]
              })
              wx.showToast({
                title: '当前时间段已经被订购 请重新选择时间段订购',
                icon: 'error',
                duration: 2000
              })
            }
        }
     })
     }
     }
  },
  /* 小程序1.0版本
   * 选择店铺后返回上一级
   */
  navigateBack() {
    wx.navigateBack({
      delta: 2
    })
  },
  checkboxChange(e){
    let that = this;
    let myval=that.data.myval;
    if(typeof(e.detail.value[0])=='undefined'){
      that.setData({
        myval:null
      })
    }else{
      that.setData({
        myval:'y'
      })
    }
    console.log(myval);
  },

  onifrulesopen(e){
    let that = this;
    that.setData({
      onifrules:true
    })
  },

  onifrulesout(e){
    let that = this;
    that.setData({
      onifrules:false
    })
  },
  // 选择地图
  onselectmap(e){
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'UZRBZ-ZMW6W-6URRV-RZ7LO-N75S5-LYBMU'
    });

    wx.openLocation({        //这里要直接输入该地方的经纬度，由于每个地图得到的经纬度不一样，所以精确度会有差别，我亲测了百度地图和腾讯地图的经纬度，发现使用腾讯地图的经纬度的精确度很高，至于为什么，毕竟都是腾讯应用嘛，大家懂的！后面给大家写了一个获取腾讯地图经纬度的文章：http://www.cnblogs.com/silent007/p/9023799.html
      latitude: 23.165102,  
      longitude: 113.402726,
      name: "广州市天河时代E-PARK二期9栋2楼",
      address:"广州市天河时代E-PARK二期9栋2楼",
      scale: 28
    })

    // let that = this;
    // wx.navigateTo({
    //   url: '/pages/map/map',
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
    _this.getRoomInfo(options.id)
     var date = new Date().toISOString().substring(0, 10);
    _this.getRoomTimesInfo(options.id, date)
    _this.getGoodsList(options.id)
    _this.setData({
      openstid:options.id,
      date:date,
      userInfo: wx.getStorageSync('userInfo'),
    })
    //获取当前会议室的折扣
    wx.request({
      url: 'https://www.yulonging.com/dwweb/wxapi.ashx?cmd=GetRoomDiscount',
      data: {
        // cmd: 'GetRoomDiscount',
        token: _this.data.userInfo.token,
        RoomID: options.id
      },
      method: "get",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        console.log('折扣');
        
        console.log('options.id');
        console.log(_this.data.userInfo.token);
        console.log(res);
        console.log('折扣');
        if(res.data.STATUS=='Error'){
          wx.navigateTo({
            url: '../login/login',
          })
        }  
        _this.setData({
          dis:res.data.DATA.Discount
        })
      }
    })

    let  token=  wx.getStorageSync('token')
    wx.request({
      url: 'https://www.yulonging.com/dwweb/wxapi.ashx',
      data: {
        cmd: 'aboutme',
        token:token
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (data) {
        console.log(data.data.DATA)
        _this.setData({
          onword:data.data.DATA.RentDoc
        })
      }
    });
 
  // 实例化API核心类
  qqmapsdk = new QQMapWX({
    key: 'UZRBZ-ZMW6W-6URRV-RZ7LO-N75S5-LYBMU'
  });
  },
    // 拨打电话
    ontel(e){
      let that = this
      let  token=  wx.getStorageSync('token')
      wx.request({
        url: 'https://www.yulonging.com/dwweb/wxapi.ashx',
        data: {
          cmd: 'aboutme',
          token:token
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (data) {
          console.log(data.data.DATA)
          wx.makePhoneCall({
            phoneNumber: data.data.DATA.Mobile,
          })
        }
      });
    },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    if(_this.data.firstEnter){
      _this.getGoodsList(_this.data.roomInfo.RoomID)
      var date = new Date().toISOString().substring(0, 10);
      _this.getRoomTimesInfo(_this.data.roomInfo.RoomID, date)
    }
    _this.setData({
      firstEnter:true
    })

    // 调用地图接口
    qqmapsdk.geocoder({ //获取目标地址的地图信息，把详细地址输入address即可
      address: '广州市天河时代E-PARK二期9栋2楼',
      success: function (res) {    //返回的数据里面有该地址的经纬度
        console.log("接口调用成功返回的回调")
      },
      fail: function (res) {
        console.log("接口调用失败返回的回调")
      },
      complete: function (res) {
        console.log("接口调用结束的回调函数（调用成功、失败都会执行）")
      }
    });
   
  },

  onword(e){
    // 根据小程序官方API提供
      var that = this;
      var filePath = e.currentTarget.dataset.url;//对应的网络路径，可以是内网的或者外网
      var fileType = e.currentTarget.dataset.type; 
      wx.downloadFile({//下载对应文件
        url: filePath,
        success: function (res) {    
          var filePath = res.tempFilePath;//文件路径    
          wx.openDocument({
            filePath: filePath,   // 装载对应文件的路径
            fileType: fileType,   // 指定打开的文件类型
            showMenu: true,       // 右上角的菜单转发分享操作
            success: function (res) {
              console.log("打开成功");
            },
            fail: function (res) {
              console.log(res);
            }
          })   
        },
        fail: function (res) {
          console.log(res);
        }
      })       
  
    },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})